import {Divider, message, Button} from 'antd';
import React, {useState, useRef} from 'react';
import ProTable, {ActionType, ProColumns} from '@ant-design/pro-table';
import {
  UserCreateParam,
  UserToggleParam,
  UserShowParam,
  UserRoleSetParam,
  PasswordSetParam
} from "@/pages/UsersMng/data";
import {addUser, toggleUser, queryUsers, modifyUser, setPassword} from "@/pages/UsersMng/service";
import {PageContainer} from "@ant-design/pro-layout";
import {PlusOutlined} from '@ant-design/icons';
import CreateForm from './components/CreateForm';
import RoleForm from './components/RoleForm';
import ToggleForm from './components/ToggleForm';
import PasswordForm from './components/PasswordForm';

const handleCreateUser = async (fields: UserCreateParam) => {
  const hide = message.loading('正在创建用户...');
  try {
    await addUser({...fields});
    hide();
    message.success('用户创建成功。');
    return true;
  } catch (error) {
    hide();
    message.error('用户创建失败。');
    return false;
  }
};

const handleToggleUser = async (fields: UserToggleParam) => {
  let hidingMsg; let successMsg; let failMsg: string;
  if (fields.isEnabled) {
    hidingMsg = "正在disable用户...";
    successMsg = "成功disable用户";
    failMsg = "fail在disable用户";
  } else {
    hidingMsg = "正在enable用户..."
    successMsg = "成功enable用户"
    failMsg = "fail在enable用户";
  }
  const hide = message.loading(hidingMsg);

  try {
    await toggleUser({...fields});
    hide();
    message.success(successMsg);
    return true;
  } catch (error) {
    hide();
    message.error(failMsg);
    return false;
  }
};

const handleRoleUpdate = async (fields: UserRoleSetParam) => {
  const hide = message.loading('正在修改用户...');
  try {
    await modifyUser({...fields});
    hide();
    message.success('成功修改用户role');
    return true;
  } catch (error) {
    hide();
    message.error('修改用户role失败');
    return false;
  }
}

const handlePasswordSet = async (fields: PasswordSetParam) => {
  const hide = message.loading('正在设置密码...');
  try {
    await setPassword({...fields});
    hide();
    message.success('设置密码成功');
    return true;
  } catch (error) {
    hide();
    message.error('设置密码失败');
    return false;
  }
}


const TableList: React.FC = () => {
  const [createUserModalVisible, setCreateUserModalVisible] = useState<boolean>(false);

  const [roleModalVisible, setRoleModalVisible] = useState<boolean>(false);
  const [roleValues, setRoleValues] = useState<UserRoleSetParam>({});

  const [passwordModalVisible, setPasswordModalVisible] = useState<boolean>(false);
  const [passwordValues, setPasswordValues] = useState<PasswordSetParam>({});

  const [toggleUserModalVisible, setToggleUserModalVisible] = useState<boolean>(false);
  const [toggleUserValues, setToggleUserValues] = useState<UserToggleParam>({});
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<UserShowParam>[] = [
    {title: 'id', dataIndex: 'id'},
    {title: 'name', dataIndex: 'name'},
    {title: 'login', dataIndex: 'loginName'},
    {title: 'role', dataIndex: 'role'},
    {title: 'createdAt', dataIndex: 'date', valueType: 'dateTime'},
    {title: 'enabled', dataIndex: 'isEnabled', valueEnum: {true: {text: 'true', status: 'Success'}, false: {text: 'false', status:'Warning'}}},
    {title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      key: 'operation',
      render: (_, record) => {
        const toggleUserMsg = record.isEnabled ? '停用' : '开启';
        let newRole: string;
        if (record.role === 'user') {
          newRole = 'admin';
        } else {
          newRole = 'user';
        }
        return (
          <>
            <a onClick={() => {
              setToggleUserModalVisible(true);
              setToggleUserValues({
                id: record.id,
                loginName: record.loginName,
                name: record.name,
                role: record.role,
                isEnabled: record.isEnabled,
              });
            }}>{toggleUserMsg}</a>
            <Divider type="vertical" />
            <a onClick={() => {
              setRoleModalVisible(true);
              setRoleValues({
                id: record.id,
                loginName: record.loginName,
                oldRole: record.role,
                newRole,
              });
            }}>权限</a>
            <Divider type="vertical" />
            <a onClick={() => {
              setPasswordModalVisible(true);
              setPasswordValues({
                id: record.id,
                loginName: record.loginName,
              });
            }}>密码</a>
            </>
        );
      },
},
];

  return (
    <PageContainer>
      <ProTable<UserShowParam>
        actionRef={actionRef}
        rowKey="id"
        request={() => queryUsers()}
        columns={columns}
        search={false}
        options={false}
        toolBarRender={() => [
          <Button key="1" type="primary" onClick={() => setCreateUserModalVisible(true)}>
            <PlusOutlined /> 新用户
          </Button>,
        ]}
      />

      <CreateForm
        onSubmit={async (value) => {
          const success = await handleCreateUser(value);
          if (success) {
            setCreateUserModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => setCreateUserModalVisible(false)}
        createUserModalVisible={createUserModalVisible}
      />

      {toggleUserValues && Object.keys(toggleUserValues).length ? (
        <ToggleForm
          onSubmit={async (value) => {
            const success = await handleToggleUser(value);
            if (success) {
              setToggleUserModalVisible(false);
              setToggleUserValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            setToggleUserModalVisible(false);
            setToggleUserValues({});
          }}
          toggleUserModalVisible={toggleUserModalVisible}
          values={toggleUserValues}
        />
      ) : null}

      {roleValues && Object.keys(roleValues).length ? (
        <RoleForm
          onSubmit={async (value) => {
            const success = await handleRoleUpdate(value);
            if (success) {
              setRoleModalVisible(false);
              setRoleValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            setRoleModalVisible(false);
            setRoleValues({});
          }}
          roleModalVisible={roleModalVisible}
          values={roleValues}
        />
      ) : null}

      {passwordValues && Object.keys(passwordValues).length ? (
        <PasswordForm
          onCancel={() => {
            setPasswordModalVisible(false);
            setPasswordValues({});
          }}
          onSubmit={async (value) => {
            const success = await handlePasswordSet(value);
            if (success) {
              setPasswordModalVisible(false);
              setPasswordValues({})
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          passwordModalVisible={passwordModalVisible}
          values={passwordValues}/>
      ) : null}
    </PageContainer>
  )
};

export default TableList;
